import { withMiddleware } from '@/lib/middleware/entry';
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { hashPassword } from '@/utils/password';
import { generateToken } from '@/utils/jwt';

async function handlePost(request: NextRequest) {
  const { email, password, username } = await request.json();

  if (!email || !password || !username) {
    return NextResponse.json({ error: '邮箱、密码和用户名不能为空' }, { status: 400 });
  }

  const existingUser = await prisma.user.findFirst({
    where: {
      OR: [
        { email },
        { username },
      ],
    },
  });

  if (existingUser) {
    return NextResponse.json({ error: '邮箱或用户名已被注册' }, { status: 409 });
  }

  const hashedPassword = await hashPassword(password);

  const user = await prisma.user.create({
    data: {
      email,
      username,
      password: hashedPassword,
    },
  });

  const token = generateToken(user);

  const { password: _, ...userWithoutPassword } = user;

  return {
    message: '注册成功',
    token,
    user: userWithoutPassword,
  };
}

export const POST = withMiddleware(handlePost);